<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class VerifyLogin extends CI_Controller {

 function __construct()
 {
   parent::__construct();
 }

 function index()
 {
   //This method will have the credentials validation
   $this->load->library('form_validation');

   $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
   $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');

   if($this->form_validation->run() == FALSE)
   {
     //Field validation failed.  User redirected to login page
	 $data['title'] = 'Login';
     $this->load->view('login_view',$data);
   }
   else
   {
     //Go to private area
	 $session_data = $this->session->userdata('logged_in');
     $statut = $session_data['statut'];
     redirect("espace_".$statut, 'refresh');
   }

 }

 function check_database($password)
 {
   //Field validation succeeded.  Validate against database
   $username = $this->input->post('username');
   $mdp = $this->input->post('password');
   $mdp = md5($mdp);
   //query the database
   $query = $this->doctrine->em->createQuery("SELECT u,v FROM visiteur u JOIN u.visreg v where u.vislogin='".$username."' AND u.vismdp='".$mdp."'");
   $result = $query->getResult();

   if($result)
   {
     $sess_array = array();
     foreach($result as $row)
     {
       $sess_array = array(
         'id' => $row->getVismatricule(),
		 'username' => $row->getVislogin(),
         'nom' => $row->getVisnom(),
		 'prenom' => $row->getVisprenom(),
		 'statut' => $row->getVisstatut(),
		 'region' => $row->getVisreg()->getRegcode(),
		 'secteur' => $row->getVisreg()->getSeccode()->getSeccode()
       );
       $this->session->set_userdata('logged_in', $sess_array);
     }
     return TRUE;
   }
   else
   {
     $this->form_validation->set_message('check_database', 'Invalid username or password');
     return false;
   }
 }
}
?>